﻿using UnityEngine;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

public class UIResourcesStepDowanload : MonoBehaviour 
{
	//所有列表
	//0：进入游戏前必须下载完成的
	//1：开启游戏前必须下载完成的，包含常规UI、当前场景UI、已开启功能（按等级）UI、窗口配置
	//2：其他场景UI
	//3：未开启功能UI
	//4：可动态下载UI
	
	private static UIResourcesStepDowanload instance;
	
	private readonly string fitName = ".uitresource";
	private char[] pathRootStart;

	public List<UIResourceInfo> allList = new List<UIResourceInfo>();		//所有资源列表   
	private string allListPath = "system/UI_allList.xml.zip";
	
	public List<UIResourceInfo> launchList = new List<UIResourceInfo>();	//这个列表交给launcer处理即可
	private string launchListPath = "system/UI_launchList.xml.zip";
	
	public List<UIResourceInfo> playBaseList = new List<UIResourceInfo>();	//进入游戏时加载的基本列表
	private string playBaseListPath = "system/UI_playBaseList.xml.zip";
	
	public List<UIResourceInfo> scenesList = new List<UIResourceInfo>();		//场景相关资源列表
	private string scenesListPath = "system/UI_scenesList.xml.zip";
	
	public List<UIResourceInfo> levelList = new List<UIResourceInfo>();		//等级相关资源
	private string levelListPath = "system/UI_levelList.xml.zip";
	
	public List<UIResourceInfo> asyncList = new List<UIResourceInfo>();		//支持代码动态加载的相关资源
	private string asyncListPath = "system/UI_asyncList.xml.zip";
	
	public List<UIResourceInfo> playList = new List<UIResourceInfo>();		//进入下一步游戏前需要下载的队列
	public List<UIResourceInfo> waitingList = new List<UIResourceInfo>();	//待加载列表, 包括必须加载的资源和后台预加载资源
	
	public bool inited;													//是否初始化
	public bool isLaunching = true;										//是否正在Lanch
	public DowanLoadState loadState = DowanLoadState.launching;			//自动加载状态
	
	void Awake()
	{
		instance = this;
	}
	
	public static UIResourcesStepDowanload GetInst()
	{
		return instance;
	}
	
	bool canPreLoad = false;
	public void StartPreLoad()
	{
		canPreLoad = true;
		if(IsInvoking("CheckWaitingList"))
			InvokeRepeating("CheckWaitingList", 1, 5.0f);
	}
	
	public bool bServerResourceLoading
	{
		get
		{
			return playList.Count > 0;
		}
	}
		
	
	private WebDownload wd;
	public void Init()
	{
//		StartCoroutine("DelayInit");
	}
	
	IEnumerator DelayInit()
	{
		wd = WebDownload.GetInstance();
		while(!wd.binit)
			yield return 0;
		
		InitPath();
		
		LoadLaunchList();
		LoadPlayBaseList();
		LoadLevelList();
		LoadScenesList();
		LoadAsyncList();
		LoadWaitingList();
		
		if(!HasAllFiles())
		{
			if(launchList.Count > 0)
			{
				SetDowanLoadState(DowanLoadState.launching);
			}
//			else if(playBaseList.Count > 0)
//			{
//				isLaunching = false;
//				SetDowanLoadState(DowanLoadState.Logining);
//			}
			else
			{
				isLaunching = false;
				SetDowanLoadState(DowanLoadState.NormalPlaying);
			}
			
//			InvokeRepeating("CheckWaitingList", 1, 5.0f);
		}
		else
		{
			isLaunching = false;
		}
		
		inited = true;
	}

	[ContextMenu("InitPath")]
	public void InitPath()
	{
		allListPath = (GameResources.RootPath + allListPath).ToLower();
		launchListPath = (GameResources.RootPath + launchListPath).ToLower();
		playBaseListPath = (GameResources.RootPath + playBaseListPath).ToLower();		
		levelListPath = (GameResources.RootPath + levelListPath).ToLower();
		scenesListPath = (GameResources.RootPath + scenesListPath).ToLower();
		asyncListPath = (GameResources.RootPath + asyncListPath).ToLower();
		
		pathRootStart = GameResources.RootPath.ToLower().ToCharArray();
		
		//删除多余文件
//		string allPath = allListPath.Substring(0, allListPath.Length - 4);
//		if(File.Exists(allPath))
//			File.Delete(allPath);
//		
//		string launchPath = launchListPath.Substring(0, launchListPath.Length - 4);
//		if(File.Exists(launchPath))
//			File.Delete(launchPath);
//		
//		string playbasePath = playBaseListPath.Substring(0, playBaseListPath.Length - 4);
//		if(File.Exists(playbasePath))
//			File.Delete(playbasePath);
//		
//		string levelPath = levelListPath.Substring(0, levelListPath.Length - 4);
//		if(File.Exists(levelPath))
//			File.Delete(levelPath);
//		
//		string scenePath = scenesListPath.Substring(0, scenesListPath.Length - 4);
//		if(File.Exists(scenePath))
//			File.Delete(scenePath);
//		
//		string asyncPath = asyncListPath.Substring(0, asyncListPath.Length - 4);
//		if(File.Exists(asyncPath))
//			File.Delete(asyncPath);
	}

	//检测是否所有文件都已下载
	bool HasAllFiles()
	{
//		foreach(UIResourceInfo info in launchList)
//		{
//			string filePath = GameResources.rootPath + info.localPath;
//			if(!File.Exists(filePath))
//				return false;
//			
//			string extension = Path.GetExtension(filePath);
//			if(extension == ".zip")
//			{
//				string truePath = filePath.Substring(0, filePath.Length - 4);
//				if(!File.Exists(truePath))
//					UnCompress.UnCompressFile(filePath, truePath);
//			}
//		}
//		
//		foreach(UIResourceInfo info in playBaseList)
//		{
//			string filePath = GameResources.rootPath + info.localPath;
//			if(!File.Exists(filePath))
//				return false;
//			
//			string extension = Path.GetExtension(filePath);
//			if(extension == ".zip")
//			{
//				string truePath = filePath.Substring(0, filePath.Length - 4);
//				if(!File.Exists(truePath))
//					UnCompress.UnCompressFile(filePath, truePath);
//			}
//		}
//		
//		foreach(UIResourceInfo info in scenesList)
//		{
//			string filePath = GameResources.rootPath + info.localPath;
//			if(!File.Exists(filePath))
//				return false;
//			
//			string extension = Path.GetExtension(filePath);
//			if(extension == ".zip")
//			{
//				string truePath = filePath.Substring(0, filePath.Length - 4);
//				if(!File.Exists(truePath))
//					UnCompress.UnCompressFile(filePath, truePath);
//			}
//		}
//		
//		foreach(UIResourceInfo info in levelList)
//		{
//			string filePath = GameResources.rootPath + info.localPath;
//			if(!File.Exists(filePath))
//				return false;
//			
//			string extension = Path.GetExtension(filePath);
//			if(extension == ".zip")
//			{
//				string truePath = filePath.Substring(0, filePath.Length - 4);
//				if(!File.Exists(truePath))
//					UnCompress.UnCompressFile(filePath, truePath);
//			}
//		}
		
		//直接检测是否还有文件需要下载
		if(waitingList.Count > 0)
			return false;
			
		loadState = DowanLoadState.NormalPlaying;
//		CancelInvoke("CheckPlayList");
//		CancelInvoke("CheckWaitingList");
		return true;
	}
	
	//将列表中的资源按照文件及版本清理掉已经存在的
	void CheckFileAndVersionExists(ref List<UIResourceInfo> list)
	{
		//调整url,下载时保留原路径，下载完后存小写
//		foreach(UIResourceInfo info in list)
//		{
//			info.localPath = info.localPath.Trim();
//			info.localPath = info.localPath.Replace("%20"," ");
//			info.localPath = info.localPath.Replace('\\', '/');
//			info.localPath = info.localPath.ToLower();
//		}
		
		//暂时不用做版本检测，Launcher会把不一致的版本文件删掉
		for(int i = 0; i < list.Count;)
		{
			UIResourceInfo info = list[i];
			info.localPath = info.localPath.ToLower();
		
			string filePath = (GameResources.RootPath + info.localPath).ToLower();			
			string extension = Path.GetExtension(filePath);
			
			if(extension == ".zip")
			{
				string truePath = filePath.Substring(0, filePath.Length - 4);
				if(File.Exists(truePath))
				{
					list.RemoveAt(i);
				}
				else
				{
					if(File.Exists(filePath))
					{
//						UnCompress.UnCompressFile(filePath, truePath);
						list.RemoveAt(i);
					}
					else
					{
						i++;
					}
				}
			}
			else
			{
				if(File.Exists(filePath))
					list.RemoveAt(i);
				else
					i++;
			}
		}
	}
	
	//更新器需要下载的列表，这个正常情况下应该得到的是空
	void LoadLaunchList()
	{
		if(File.Exists(launchListPath))
			launchList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(launchListPath, Encoding.UTF8));
		else
		{
			string launPath = launchListPath.Substring(0, launchListPath.Length - 4);
			launchList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(launPath, Encoding.UTF8));
		}
			
		
		CheckFileAndVersionExists(ref launchList);
		launchList.Sort(Comparison);
	}
	
	//基本列表
	void LoadPlayBaseList()
	{
		if(File.Exists(playBaseListPath))
			playBaseList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(playBaseListPath, Encoding.UTF8));
		else
		{
			string playbasePath = playBaseListPath.Substring(0, playBaseListPath.Length - 4);
			playBaseList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(playbasePath, Encoding.UTF8));
		}
		
		CheckFileAndVersionExists(ref playBaseList);		
		playBaseList.Sort(Comparison);
	}
	
	void LoadScenesList()
	{
		if(File.Exists(scenesListPath))
			scenesList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(scenesListPath, Encoding.UTF8));
		else
		{
			string scenesPath = scenesListPath.Substring(0, scenesListPath.Length - 4);
			scenesList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(scenesPath, Encoding.UTF8));
		}
		
		CheckFileAndVersionExists(ref scenesList);
		scenesList.Sort(Comparison);
	}
	
	void LoadLevelList()
	{
		if(File.Exists(levelListPath))
			levelList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(levelListPath, Encoding.UTF8));	
		else
		{
			string levelPath = levelListPath.Substring(0, levelListPath.Length - 4);
			levelList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(levelPath, Encoding.UTF8));
		}
		
		CheckFileAndVersionExists(ref levelList);
		levelList.Sort(Comparison);
	}
	
	void LoadAsyncList()
	{
		if(File.Exists(asyncListPath))
			asyncList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(asyncListPath, Encoding.UTF8));
		else
		{
			string asyncPath = asyncListPath.Substring(0, asyncListPath.Length - 4);
			asyncList = XML<UIResourceInfo>.LoadListFromText(UnCompress.GetText(asyncPath, Encoding.UTF8));
		}
		
		CheckFileAndVersionExists(ref asyncList);
		asyncList.Sort(Comparison);
	}
	
	void LoadWaitingList()
	{
		//先把所有资源加入等待下载列表中,顺序被改，这个与优先级有关
		foreach(UIResourceInfo info in launchList)
			waitingList.Add(info);
		
		foreach(UIResourceInfo info in playBaseList)
			waitingList.Add(info);
		
		foreach(UIResourceInfo info in levelList)
			waitingList.Add(info);
		
		foreach(UIResourceInfo info in scenesList)
			waitingList.Add(info);
		
		//支持动态加载的放在最后
		foreach(UIResourceInfo info in asyncList)
			waitingList.Add(info);
	}
	public void LoadNeed()
	{
		for(int i = 0; i < playList.Count;i++)
		{			
			UIResourceInfo info = playList[i];
			if(!info.isdownloading)
			{
				info.isdownloading = true;
				string remoteUrl = (wd.webservername + info.localPath).ToLower();
				wd.AddDownLoad(remoteUrl);
			}
		}
	}
	void Update()
	{
		for(int i = 0; i < playList.Count;)
		{
			UIResourceInfo info = playList[i];
			if(info.isdownloading)
			{
				string file = (GameResources.RootPath + info.localPath).ToLower();
				if(file.EndsWith(".zip"))
					file = file.Substring(0, file.Length - 4);
					
				//完成下载后检测预加载
				if(File.Exists(file))
				{
					DebugDownLoadOver(info.localPath);
					playList.RemoveAt(i);
					
					if(playList.Count < 1)
					{
						if(loadState == DowanLoadState.launching)
						{
							isLaunching = false;
							SetDowanLoadState(DowanLoadState.NormalPlaying);
							//SetDowanLoadState(DowanLoadState.Logining);
						}
//						else
//						{					
//							SetDowanLoadState(DowanLoadState.NormalPlaying);
//						}
					}
				}
				else
				{
					i++;
				}
			}
			else
			{
				i++;
			}
		}
		
		
		for(int i = 0; i < waitingList.Count;)
		{			
			UIResourceInfo info = waitingList[i];
			if(info.isdownloading)
			{
				//文件已经下载完成并解压完成，剔除
				string file = (GameResources.RootPath + info.localPath).ToLower();
				if(file.EndsWith(".zip"))
					file = file.Substring(0, file.Length - 4);
				
				//完成下载后检测预加载
				if(File.Exists(file))
				{
					DebugDownLoadOver(info.localPath);
					waitingList.RemoveAt(i);		
				}
				else
					i++;
			}
			else
			{
				i++;
			}
		}
	}
	
	// 预加载采取每5秒处理1个的方式
	int lastHeroLevel = -1;
	int currentHeroLevel = 0;	//这里设置成不一样，可以让首次预加载的时候把非当前场景的资源排到后面,优先加载等级资源
	void CheckWaitingList()
	{
		//非常规状态（即没有必须下载资源状态)时才开启预加载，这样可以防止预加载抢占线程
		if(loadState != DowanLoadState.NormalPlaying)
			return;
		
		//如果有必须下载的资源，预加载让出位置
		if(waitingList.Count > 0 && playList.Count < 1 && !wd.IsDownloadListBusy())
		{
			// 将预加载的等级队列排到场景之前，防止来回排序
			// 根据当前等级排序预加载队列,采用等级缓存，防止队列排序的性能消耗
//			if(lastHeroLevel != currentHeroLevel)
//			{
//				lastHeroLevel = currentHeroLevel;
//				SortWaitingListByLevel();
//			}
			
			//根据优先级下载，数值越小，优先级越高,这里的优先级只是做了优先一步扔到下载队列
			int minPriority = int.MaxValue;
			UIResourceInfo nextInfo = null;
			
			//根据优先级别来，优先级
			for(int i = 0; i < waitingList.Count; i++)
			{
				UIResourceInfo info = waitingList[i];
				//找到1个不在下载状态的添加到预加载队列，并不立即从队列中删除，这样可以保证检测是否加载完所有资源
				if(!info.isdownloading)
				{
					if(info.Priority < minPriority)
					{
						minPriority = info.Priority;
						nextInfo = info;
					}
				}
			}
			
			if(nextInfo != null)
			{
				nextInfo.isdownloading = true;				
				wd.AddDownLoad((wd.webservername + nextInfo.localPath).ToLower());
			}
		}
	}
	
	void DebugDownLoadOver(string filePath)
	{
		bool findInResouceList = false;
		//清除待下载的队列
		foreach(UIResourceInfo info in playList)
		{
			if(info.localPath.ToLower() == filePath.ToLower())
			{				
				Debug.Log("完成基础UI资源下载：" + filePath + "，剩余个数：" + (playList.Count - 1));
				findInResouceList = true;

				break;
			}
		}
		
		foreach(UIResourceInfo info in waitingList)
		{
			if(info.localPath.ToLower() == filePath.ToLower())
			{
				if(!findInResouceList)
				{
					Debug.Log("完成预加载UI资源下载：" + filePath + "，剩余个数：" + (waitingList.Count - 1));
				}
				findInResouceList = true;
				
				break;
			}
		}
	}
	
//	void OnGUI()
//	{
//		for(int i =0;i< playList.Count;i++)
//		{
//			UIResourceInfo uinfo = playList[i];
//			GUILayout.Label(uinfo.localPath.ToString());
//		}
//	}
	//真正下载完成后才从列表中清除
	public void DownLoadOver(string filePath)
	{
		bool findInResouceList = false;
		//清除待下载的队列
		foreach(UIResourceInfo info in playList)
		{
			if(info.localPath.ToLower() == filePath)
			{
//				playList.Remove(info);
				
//				Debug.Log("完成基础UI资源下载：" + filePath);
//				Debug.Log("剩余基础UI资源个数：" + playList.Count);
				findInResouceList = true;
				
				break;
			}
		}
		
		foreach(UIResourceInfo info in waitingList)
		{
			if(info.localPath.ToLower() == filePath)
			{
//				waitingList.Remove(info);
				
//				if(!findInResouceList)
//					Debug.Log("完成预加载UI资源下载：" + filePath);				
				findInResouceList = true;
				
				break;
			}
		}
		
		if(findInResouceList && !wd.IsUesLuancher)
		{
			//解压
			string file = GameResources.RootPath + filePath.ToLower();
			if(file.EndsWith(".zip"))
			{
				UnCompress.UnCompressFile(file, file.Substring(0, file.Length - 4).ToLower());
				File.Delete(file);
			}
		}
		
		//下载的是UI资源时
//		if(findInResouceList)
//		{			
//			//解压
//			string file = GameResources.rootPath + filePath.ToLower();
//			if(file.EndsWith(".zip"))
//			{
//				UnCompress.UnCompressFile(file, file.Substring(0, file.Length - 4).ToLower());
//				File.Delete(file);
//			}
//			
//			if(playList.Count < 1)
//			{
//				if(loadState == DowanLoadState.launching)
//				{
//					isLaunching = false;
//					SetDowanLoadState(DowanLoadState.Logining);
//				}
//				else
//				{					
//					SetDowanLoadState(DowanLoadState.NormalPlaying);
//				}
//			}
//		}
	}
	
	//下载失败
	public void DownLoadError(string filePath)
	{				
		//必须下载的资源,继续再次重下
		foreach(UIResourceInfo info in playList)
		{
			if(info.localPath.ToLower() == filePath)
			{
				Debug.Log("资源下载失败：" + filePath + ",重新开启下载！");
				wd.AddDownLoad(wd.webservername + info.localPath);
				return;
			}
		}
		
		//后台预加载的暂停其下载状态并可调整下优先级
		foreach(UIResourceInfo info in waitingList)
		{
			if(info.localPath.ToLower() == filePath)
			{
				Debug.Log("资源下载失败：" + filePath + ",稍后重新开启下载！");
				info.isdownloading = false;
				info.Priority++;
				return;
			}
		}
	}
	
	//优先预加载2个等级内的资源
	void SortWaitingListByLevel()
	{
//		THero hero = THero.GetInstance();
//		if(hero == null)
//			return;
//		
//		int currentLevel = (int)hero.Data.Level;
		//将场景整体移动到等级队列后面
//		if(TMapManager.curMap == null)
//		{
//			//获取场景队列
//			List<UIResourceInfo> sceneInfos = new List<UIResourceInfo>();
//			for(int i = 0; i < waitingList.Count;)
//			{
//				UIResourceInfo info = waitingList[i];
//				if(info.type == ResourceType.Scene)
//				{
//					sceneInfos.Add(info);
//					waitingList.RemoveAt(i);
//				}
//				else
//				{
//					i++;
//				}
//			}
//			
//			//找到等级队列的最后1个
//			int levelEndIndex = 0;
//			for(int i = waitingList.Count - 1; i >= 0; i--)
//			{
//				UIResourceInfo info = waitingList[i];
//				if(info.type == ResourceType.Level)
//				{
//					levelEndIndex = i;
//					break;
//				}
//			}
//			
//			//将场景队列添加到等级队列后
//			for(int i = 0; i < sceneInfos.Count; i++)
//				waitingList.Insert(i + levelEndIndex + 1, sceneInfos[i]);
//		}
//		//将非当前场景信息整体移动到等级队列后面
//		else
//		{
//			int mapID = TMapManager.curMap.mID;
//			
//		}
	}
	
	//更新当前下载策略
	public void SetDowanLoadState(DowanLoadState state)
	{
		//已经完成下载后不触发预加载
		if(HasAllFiles())
			return;
		
		loadState = state;
		switch(loadState)
		{
		case DowanLoadState.launching:
			GetLaunchingList(ref playList);
			break;			
		case DowanLoadState.Logining:
			GetLoginingList(ref playList);
			break;			
		case DowanLoadState.SceneLoading:
			GetSceneLoadingList(ref playList);
			break;
		case DowanLoadState.LevelUping:
			GetLevelUpingList(ref playList);
			break;
		case DowanLoadState.NormalPlaying:
			if(!IsInvoking("CheckWaitingList") && canPreLoad)
				InvokeRepeating("CheckWaitingList", 1, 5.0f);
			break;
		default:
			break;
		}
		
		if(playList.Count < 1)
			loadState = DowanLoadState.NormalPlaying;
		else
			LoadNeed();
	}
	
	void GetLaunchingList(ref List<UIResourceInfo> list)
	{
		for(int i = 0; i < waitingList.Count;)
		{
			UIResourceInfo info = waitingList[i];
			if(info.type == ResourceType.Launcher)
			{
				list.Add(info);
				waitingList.RemoveAt(i);
			}
			else
			{
				i++;
			}
		}
	}
	
	void GetLoginingList(ref List<UIResourceInfo> list)
	{		
		for(int i = 0; i < waitingList.Count;)
		{
			UIResourceInfo info = waitingList[i];
			if(info.type == ResourceType.PlayGame)
			{
				list.Add(info);
				waitingList.RemoveAt(i);
			}
			else
			{
				i++;
			}
		}
	}
	
	void GetSceneLoadingList(ref List<UIResourceInfo> list)
	{		
		GetLoginingList(ref list);
		
//		int mapID = LoaderManager.GetInst().delayloadid;
		int mapID = 0;
		
		Debug.Log("下载场景资源: mapID=" + mapID);		
		for(int i = 0; i < waitingList.Count;)
		{
			UIResourceInfo info = waitingList[i];
			if(info.type == ResourceType.Scene && info.sceneID == mapID)
			{
				list.Add(info);
				waitingList.RemoveAt(i);
			}
			else
			{
				i++;
			}
		}

		GetLevelUpingList(ref list);
	}
	
	void GetLevelUpingList(ref List<UIResourceInfo> list)
	{
//		THero hero = THero.GetInstance();
		int currentLevel = 1;
//		if(hero == null)
//			currentLevel = (int)GameInfo.RoleInfoList.list[SelectEnterGameWindow.GetInst().m_RoleXuanZhong].RoleLevel;
//		else
//			currentLevel = (int)hero.Data.Level;
		
		Debug.Log("下载等级资源: currentLevel=" + currentLevel);
		for(int i = 0; i < waitingList.Count;)
		{
			UIResourceInfo info = waitingList[i];
			if(info.type == ResourceType.Level && info.level <= currentLevel + 5)
			{
				list.Add(info);
				waitingList.RemoveAt(i);
			}
			else
			{
				i++;
			}
		}
	}
	
	//越是基础的资源放在前面
	int Comparison(UIResourceInfo a, UIResourceInfo b)
	{
		//先比较资源类型
		if(a.type < b.type) return -1;
		if(a.type > b.type) return 1;
		
				
		//等级类型的按照等级低到高
		if(a.type == ResourceType.Level)
		{
			if(a.level < b.level) return -1;
			if(a.level > b.level) return 1;
		}
		//场景类型的按照场景ID低到高
		else if(a.type == ResourceType.Scene)
		{
			if(a.sceneID < b.sceneID) return -1;
			if(a.sceneID > b.sceneID) return 1;
		}
		
		//最后按照内部优先级
		if(a.Priority < b.Priority) return -1;
		if(a.Priority > b.Priority) return 1;
		
		//支持动态加载的直接放在最后，不做调整

		return 0;	
	}
	
	[ContextMenu("RestAllUIResourceInfo")]
	public void RestAllUIResourceInfo()
	{
		allList.Clear();
		
		string[] files = Directory.GetFiles(GameResources.RootPath + "GameResources/UI/", "*", SearchOption.AllDirectories);
		foreach(string file in files)
		{
			string extension = Path.GetExtension(file);
			if(extension != fitName && extension != ".lua")
				continue;
			
			string localPath = file.TrimStart(pathRootStart).Replace('\\', '/');
			if(extension != ".lua")
				localPath += ".zip";
			
			UIResourceInfo info = new UIResourceInfo();
			info.localPath = localPath;
			
			if(info.localPath.StartsWith("GameResources/UI/Dep/Window/"))
				info.type = ResourceType.Launcher;
			else if(info.localPath.EndsWith(".lua"))
				info.type = ResourceType.Launcher;
			
			allList.Add(info);
		}
		
		XML<UIResourceInfo>.SaveListAtPath(allList, allListPath);
	}
	
	[ContextMenu("UpdateAllUIResourceInfo")]
	public void UpdateAllUIResourceInfo()
	{
		allList.Clear();
		
		List<UIResourceInfo> oldAlllist = XML<UIResourceInfo>.LoadListFromPath(allListPath);
		
		for(int i = 0; i < oldAlllist.Count;)
		{
			string file = GameResources.RootPath + oldAlllist[i].localPath;
			if(file.EndsWith(".zip"))
				file = file.Substring(0, file.Length - 4);
			if(!File.Exists(file))
				oldAlllist.RemoveAt(i);
			else
				i++;
		}
		
		string[] files = Directory.GetFiles(GameResources.RootPath + "GameResources/UI/", "*", SearchOption.AllDirectories);
		foreach(string file in files)
		{
			//屏蔽掉打包资源和其他无用资源
			string extension = Path.GetExtension(file);
			if(extension != fitName && extension != ".lua")
				continue;
			
			string localPath = file.TrimStart(pathRootStart).Replace('\\', '/');
			if(extension != ".lua")
				localPath += ".zip";
			
			UIResourceInfo info = null;
			foreach(UIResourceInfo oldInfo in oldAlllist)
			{
				if(oldInfo.localPath == localPath)
				{
					info = oldInfo;
					break;
				}
			}			
			
			if(info == null)
			{
				info = new UIResourceInfo();
				info.localPath = localPath;
			}
			
			//窗口配置和lua文件都作为必须加载的文件
			if(info.localPath.StartsWith("GameResources/UI/Dep/Window/"))
			{
				info.type = ResourceType.Launcher;
				info.setOK = true;
			}
			//自动识别地图编号
			else if(info.localPath.StartsWith("GameResources/UI/Base/Material/Map/"))
			{
				int index1 = info.localPath.LastIndexOf('-');
				int index2 = info.localPath.IndexOf('.');
				int mapID = 0;
				if(int.TryParse(info.localPath.Substring(index1 + 1, index2 - index1 - 1), out mapID))
				{
					info.type = ResourceType.Scene;
					info.sceneID = mapID;
					info.setOK = true;
				}
			}
			else if(info.localPath.EndsWith(".lua"))
			{
				info.type = ResourceType.Launcher;
				info.setOK = true;
			}
			
			if(info.type == ResourceType.Launcher && !info.setOK)
				info.type = ResourceType.PlayGame;
			
			allList.Add(info);
		}
		
		XML<UIResourceInfo>.SaveListAtPath(allList, allListPath);
	}
	
	[ContextMenu("UpdateXMLs")]
	public void UpdateXMLs()
	{		
		allList = XML<UIResourceInfo>.LoadListFromPath(allListPath);
		launchList.Clear();
		playBaseList.Clear();
		levelList.Clear();
		scenesList.Clear();
		asyncList.Clear();
			
		for(int i = 0; i < allList.Count;)
		{
			UIResourceInfo info = allList[i];
			
			string file = info.localPath;
			if(file.EndsWith(".zip"))
				file = file.Substring(0, file.Length - 4);
			file = GameResources.RootPath + file;
			if(!File.Exists(file))
			{
				allList.RemoveAt(i);
				continue;
			}
			else
			{
				i++;
			}
				
			//窗口配置和lua文件都作为必须加载的文件
			if(info.localPath.StartsWith("GameResources/UI/Dep/Window/"))
			{
				info.type = ResourceType.Launcher;
				info.setOK = true;
			}
			//自动识别地图编号
			else if(info.localPath.StartsWith("GameResources/UI/Base/Material/Map/"))
			{
				int index1 = info.localPath.LastIndexOf('-');
				int index2 = info.localPath.IndexOf('.');
				int mapID = 0;
				if(int.TryParse(info.localPath.Substring(index1 + 1, index2 - index1 - 1), out mapID))
				{
					info.type = ResourceType.Scene;
					info.sceneID = mapID;
					info.setOK = true;
				}
			}
			else if(info.localPath.EndsWith(".lua"))
			{
				info.type = ResourceType.Launcher;
				info.setOK = true;
			}
			
			//没设置的默认添加到launcher下载列表
			if(info.setOK)
			{
				if(info.type == ResourceType.Launcher)
					launchList.Add(info);
				else if(info.type == ResourceType.PlayGame)
					playBaseList.Add(info);
				else if(info.type == ResourceType.Level)
					levelList.Add(info);
				else if(info.type == ResourceType.Scene)
					scenesList.Add(info);
				//未定义的其他文件都作为支持动态加载的文件
				else
					asyncList.Add(info);
			}
			else
			{
				info.type = ResourceType.Async;
				asyncList.Add(info);
//				playBaseList.Add(info);
			}
		}
		
		XML<UIResourceInfo>.SaveListAtPath(allList, allListPath);
		XML<UIResourceInfo>.SaveListAtPath(launchList, launchListPath);
		XML<UIResourceInfo>.SaveListAtPath(playBaseList, playBaseListPath);
		XML<UIResourceInfo>.SaveListAtPath(levelList, levelListPath);
		XML<UIResourceInfo>.SaveListAtPath(scenesList, scenesListPath);
		XML<UIResourceInfo>.SaveListAtPath(asyncList, asyncListPath);
	}
	
	[ContextMenu("更新所有配置")]
	public void UpdateAllXMLs()
	{
		InitPath();
		UpdateAllUIResourceInfo();
		UpdateXMLs();
	}
}

public class UIResourceInfo
{
	[XmlAttribute]
	public bool setOK;				//是否处理完
	[XmlAttribute]
	public ResourceType type = ResourceType.Async;		//加载策略类型
	[XmlAttribute]
	public int level;				//开启等级
	[XmlAttribute]
	public int sceneID;				//绑定场景
	[XmlAttribute]
	public int Priority;			//优先级别，越小优先级越高
	[XmlAttribute]
	public string localPath;		//本地相对路径
	
	[XmlIgnore]
	public bool isdownloading;		//是否正在被下载
}

public enum ResourceType
{
	Launcher = 0,						//属于必须在Lancher结束前下载完成的，等待情况：一直lauching
	PlayGame = 1,						//属于必须在开始玩游戏前下载完成的，等待情况：一直loading,该项需要后两项一起完成
	Level = 2,							//属于必须在开启对应等级功能前下载完成的，等待情况：开始游戏前，进入游戏时一直loading；游戏中开启：暂时不允许，应该提前如2等级后台下载资源
	Scene = 3,							//属于必须在进入某场景前下载完成的，等待情况：一直loading
	Async = 4,							//属于支持动态异步加载的资源，如大背景、特效等，等待情况：后台加载
}

public enum DowanLoadState
{
	launching,							//正在Lanch阶段，程序中用不到
	Logining,							//登录至游戏前
	SceneLoading,						//跳转场景，游戏中的跳转
	LevelUping,							//升级
	NormalPlaying,						//常规状态
}